import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), '../common'))
# from common import util
import logging
import traceback
import inspect
from report_system.spider import spider_config


class Task(object):

    def __init__(self, handler, interval_sec=spider_config.spider_interval_sec_, **kwargs):
        self.interval_sec_ = interval_sec
        self.handler_ = handler
        self.retry_num_ = 0
        self.req_kwargs_ = dict()
        self.rsp_kwargs_ = dict()
        req_params = ['expect_codes', 'not_expect_codes', 'max_retry', 'retry_interval_sec', 'url', 'method', 'params',
                      'data', 'headers', 'cookies', 'files', 'auth', 'timeout', 'allow_redirects', 'proxies', 'hooks',
                      'stream', 'verify', 'cert', 'json']
        for k in kwargs:
            v = kwargs[k]
            if k in req_params:
                self.req_kwargs_[k] = v
            else:
                self.rsp_kwargs_[k] = v

    def retry_num(self):
        return self.retry_num_

    def url(self):
        if 'url' in self.req_kwargs_:
            return self.req_kwargs_['url']
        return None

    def handle_rsp(self, rsp):
        sigs = inspect.signature(self.handler_).parameters
        if 'r' in sigs and 'r' not in self.rsp_kwargs_:
            self.rsp_kwargs_['r'] = rsp
        if 'url' in sigs and 'url' not in self.rsp_kwargs_:
            self.rsp_kwargs_['url'] = self.url()
        if 'task' in sigs and 'task' not in self.rsp_kwargs_:
            self.rsp_kwargs_['task'] = self
        if 'j' in sigs and 'j' not in self.rsp_kwargs_:
            try:
                j = rsp.json()
            except Exception as e:
                j = None
            self.rsp_kwargs_['j'] = j
        for k in list(self.rsp_kwargs_):
            if k not in sigs:
                self.rsp_kwargs_.pop(k)
        self.handler_(**self.rsp_kwargs_)


def main():
    pass
    # util.init_logging()


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        logging.error('异常, %s, %s' % (repr(e), traceback.format_exc()))
